import { Form, Input } from 'antd';
import { useEffect } from "react";
import { adminAPI } from "../../../apis/user";
import { rsaEncode } from "../../../utils/rsa";
import mStl from './user-form.mod.less';

export interface UserFormInfo {
  username: string;
  password: string;
  email: string;
  id: string;
}

export interface UserFormProp {
  form: any;
  isEdit?: boolean;
  userItem?: UserFormInfo|null;
  setSubmitLoading?: (loading: boolean) => void;
  onSubmitSuccess?: () => void;
}

/**
 * @desc 用户编辑
 * @param props
 * @constructor
 */
const UserForm = (props: UserFormProp) => {
  const initialValues = {};
  const defaultPwd = "******";
  const form = props.form;

  useEffect(() => {
    if(props.userItem) {
      form.setFieldsValue({
        ...props.userItem,
        password: defaultPwd
      });
    } else {
      form.setFieldsValue({
        username: '',
        password: '',
        email: ''
      });
    }
  }, [props.isEdit, props.userItem])

  /**
   * @desc 提交表单
   * @param values
   */
  const onFinish = (values: UserFormInfo) => {
    let promise;
    if (!props.isEdit) {
      promise = adminAPI.adminAdd({
        ...values,
        password: rsaEncode(values.password)
      })
    } else {
      const params: UserFormInfo = {
        ...values,
        id: (props as any).userItem.id,
      }
      if (values.password !== defaultPwd) {
        params.password = rsaEncode(values.password) as string;
      } else {
        delete (params as any)['password'];
      }
      promise = adminAPI.adminEdit(params)
    }

    if (props.setSubmitLoading) {
      props.setSubmitLoading(true);
    }

    promise.then((res: any) => {
      if (res && res.success) {
        if (props.onSubmitSuccess) {
          props.onSubmitSuccess();
        }
      }
    }).finally(() => {
      if (props.setSubmitLoading) {
        props.setSubmitLoading(false);
      }
    })
  }

  const layout = {
    labelCol: { span: 24 },
  }

  return (
    <Form
      className={mStl['user-form']}
      {...layout}
      form={form}
      name="userForm"
      size={"middle"}
      labelAlign={"right"}
      initialValues={initialValues}
      onFinish={onFinish}
    >
      <Form.Item
        label={"登录账户"}
        name="username"
        rules={[{ required: true, message: '输入登录账户' }]}
      >
        <Input placeholder={"登录账户"}/>
      </Form.Item>
      <Form.Item
        label={"电子邮箱"}
        name="email"
        rules={[
          { required: true, message: '输入电子邮箱' },
          { type: 'email', message: "格式不正确"}
        ]}
      >
        <Input placeholder={"电子邮箱"} />
      </Form.Item>
      <Form.Item
        label={"登陆密码"}
        name="password"
        rules={[{ required: true, message: '输入登录密码' }]}
      >
        <Input.Password disabled={props.isEdit} placeholder={"登录密码"} />
      </Form.Item>
    </Form>
  );
};

export default UserForm;
